<template>
    <div class="pool-list">
        <div class="move-box">
            <RiskLeftModule02
                v-model="inputValueLeft"
                @on-handleNode="clickNode"
                :treeData="treeData"
                :leftHeight="leftHgt"
                :defaultExpandedKeys="['-1']"
                :currentKey="currentKey"
            >
                <template slot="ltitle">条目权限维护</template>
            </RiskLeftModule02>

            <!-- 条目权限维护 START -->
            <template v-if="cutInfo === '全部选择'">
                <RiskRightModule02 :rightHeight="leftHgt">
                    <p slot="rtitle">条目权限维护</p>
                    <span slot="button" class="layout01-r-slot">
                        <el-button type="primary" size="mini" v-authCode.show="B_0027" @click="queryVisible = true">查询</el-button>
                    </span>
                    <slot>
                        <el-table :data="tableData" border size="mini" style="width: 100%" height="79vh">
                            <el-table-column prop="entryRoleCode" label="编号" min-width="100"> </el-table-column>
                            <el-table-column prop="entryRoleName" label="条目角色分类" min-width="120" show-overflow-tooltip> </el-table-column>
                            <el-table-column prop="createUser" label="创建人" show-overflow-tooltip v-if="showParamByDocking()"> </el-table-column>
                            <el-table-column prop="createDate" label="创建日期" show-overflow-tooltip align="center" sortable>
                                <template slot-scope="scope">
                                    <span>{{ dateFormat(scope.row.createDate) }} {{ timeFormat(scope.row.createTime) }}</span>
                                </template>
                            </el-table-column>
                            <!-- <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip align="center"> </el-table-column> -->
                        </el-table>
                    </slot>
                </RiskRightModule02>
                <!-- 查询  START -->
                <div class="query">
                    <yh-dialog drag title="条目权限维护" :visible.sync="queryVisible" width="500px">
                        <el-form label-width="120px" size="mini" ref="queryForm" :model="queryForm">
                            <el-form-item label="编号" prop="groupCode">
                                <el-input style="width: 220px" v-model="queryForm.entryRoleCode" />
                            </el-form-item>
                            <el-form-item label="条目角色分类" prop="groupName">
                                <el-input style="width: 220px" v-model="queryForm.entryRoleName" />
                            </el-form-item>
                            <el-form-item label="创建人" prop="groupName">
                                <el-input style="width: 220px" v-model="queryForm.createUser" />
                            </el-form-item>
                        </el-form>
                        <div slot="footer" class="dialog-footer">
                            <el-button size="mini" @click="queryVisible = false">取 消</el-button>
                            <el-button size="mini" @click="resetForm">重 置</el-button>
                            <el-button size="mini" type="primary" @click="searchData" v-loading="delLoading">确 定</el-button>
                        </div>
                    </yh-dialog>
                </div>
                <!-- 查询 END -->
            </template>
            <!-- 条目权限维护 END -->
            <template v-else>
                <RiskRightModule02>
                    <p slot="rtitle">条目权限维护明细</p>
                    <span slot="button" class="layout01-r-slot">
                        <el-button
                            type="primary"
                            size="mini"
                            v-authCode.show="B_0031"
                            @click="handleItemPermission(null, null, 'edit')"
                            key="table1-btn1"
                            >编辑</el-button
                        >
                        <el-button type="danger" size="mini" v-authCode.show="B_0030" @click="handleDetailRemove(-1)" key="table1-btn2"
                            >删除</el-button
                        >
                        <el-button type="primary" size="mini" v-authCode.show="B_0027" @click="queryDetailVisible = true">查询</el-button>
                    </span>
                    <slot>
                        <el-table
                            :data="tableDetailData"
                            @selection-change="handleSelectionDetailChange"
                            v-table-top="detailPage.currentPage"
                            border
                            size="mini"
                            style="width: 100%"
                            height="calc(100vh - 140px)"
                            key="detail"
                        >
                            <el-table-column
                                type="selection"
                                width="55"
                                size="mini"
                                fixed="left"
                                :selectable="
                                    row => {
                                        return !row.isDisabled;
                                    }
                                "
                            ></el-table-column>
                            <el-table-column prop="entryCode" label="条目编号" width="220" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="entryName" label="风险说明" show-overflow-tooltip> </el-table-column>
                            <el-table-column label="操作" width="120">
                                <template slot-scope="scope">
                                    <RiskIconButton
                                        type="danger"
                                        icon="el-icon-delete"
                                        topTitle="删除"
                                        :disabled="scope.row.isDisabled"
                                        v-authCode="B_0119"
                                        @on-click="handleDetailRemove(scope.row.entryCode)"
                                    />
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="block">
                            <el-pagination
                                background
                                @current-change="currentDetailChange"
                                layout="total, prev, pager, next"
                                :total="detailPage.total"
                                :page-size="detailPage.pageSize"
                                :current-page.sync="detailPage.currentPage"
                            >
                            </el-pagination>
                        </div>
                    </slot>
                </RiskRightModule02>
            </template>
        </div>

        <!-- 编辑 -->
        <yh-dialog drag title="条目绑定" :visible.sync="showModal" width="800px" v-loading="loading" class="editDialog">
            <div>
                <el-checkbox v-model="isDisabled" style="margin:10px 20px;font-weight:700">是否拥有所有条目权限</el-checkbox>
                <!-- @change="handleAllProduct" -->
                <RiskTrantable
                    leftPlaceholder="条目编号/风险说明"
                    rightPlaceholder="条目编号/风险说明"
                    :leftColumns="tranColumns"
                    :rightColumns="tranColumns"
                    :leftTableData="leftTranData"
                    :rightTableData="rightTranData"
                    :leftSearchNames="['entryCode', 'entryName']"
                    indexKey="entryCode"
                    ref="tranTable"
                    :isDisabled="isDisabled"
                    :sort="(a, b) => a.entryCode.substring(2) - b.entryCode.substring(2)"
                />
            </div>
            <div slot="footer" class="dialog-footer" style="display:flex;justify-content: flex-end;padding-right:20px">
                <el-button size="mini" @click="dialogClosed"> 取 消 </el-button>
                <el-button size="mini" type="primary" @click="editDetailDialogConfirm" v-show="operateType === 'edit'">确 定 </el-button>
            </div>
        </yh-dialog>

        <!-- 查询明细 START -->
        <div>
            <yh-dialog drag title="查询条目权限维护明细" :visible.sync="queryDetailVisible" width="500px">
                <el-form label-width="120px" size="mini" ref="queryDetailForm" :model="queryDetailForm">
                    <el-form-item label="条目编号" prop="entryCode">
                        <el-input style="width: 220px" v-model="queryDetailForm.entryCode" />
                    </el-form-item>
                    <el-form-item label="风险说明" prop="entryName">
                        <el-input style="width: 220px" v-model="queryDetailForm.entryName" />
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="queryDetailVisible = false">取 消</el-button>
                    <el-button size="mini" @click="resetForm('detail')">重 置</el-button>
                    <el-button size="mini" type="primary" @click="searchData('detail')" v-loading="delLoading">确 定</el-button>
                </div>
            </yh-dialog>
        </div>
        <!-- 查询明细 END -->

        <!-- 删除明细 START -->
        <div>
            <yh-dialog drag title="确定删除以下条目组明细信息吗？" :visible.sync="delDetailVisible" width="500px">
                <div class="remove-text">
                    <span> {{ delDetailList.join(' , ') }}</span>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="delDetailVisible = false">取 消</el-button>
                    <el-button size="mini" type="primary" @click="editDetailDialogConfirm('del')">确 定</el-button>
                </div>
            </yh-dialog>
        </div>
        <!-- 删除明细 END -->
    </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';

import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskTrantable from '@/common/components/risk-trantable.vue';
import RiskLeftModule02 from '@/common/components/risk-left-module02.vue';
import RiskRightModule02 from '@/common/components/risk-right-module02.vue';
import { getCurrentPageData, showParamByDocking, timeFormat, dateFormat } from '@/utils/tools';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

const EntryPower = {
    '001': '风控',
    '002': '投资',
    '003': '交易',
    '004': '合规风险',
};

@Component({
    name: 'ItemManage',
    components: {
        RiskLeftModule02,
        RiskRightModule02,
        RiskIconButton,
        RiskTrantable,
    },
})
export default class ItemManage extends Vue {
    showParamByDocking = showParamByDocking;
    dateFormat = dateFormat;
    timeFormat = timeFormat;
    private leftHgt: string = '100vh';
    private tableData: any[] = []; // 显示数据
    private tableDetailData: any[] = []; // 当前页明细数据
    private tableDetailDataList: any[] = []; // 明细数据

    private cutInfo: string = '全部选择'; // 当前选择节点
    private selectNode: string = ''; // 选择节点
    currentKey: string = '-1';
    private tableDataList: any[] = [
        { key: '001', entryRoleCode: '001', entryRoleName: '风控', createUser: '系统管理员', createDate: '2022-11-22', createTime: '00:15:00' },
        { key: '002', entryRoleCode: '002', entryRoleName: '投资', createUser: '系统管理员', createDate: '2022-11-22', createTime: '00:15:00' },
        { key: '003', entryRoleCode: '003', entryRoleName: '交易', createUser: '系统管理员', createDate: '2022-11-22', createTime: '00:15:00' },
        { key: '004', entryRoleCode: '004', entryRoleName: '合规风险', createUser: '系统管理员', createDate: '2022-11-22', createTime: '00:15:00' },
    ]; // 总数据
    private leftTranData: any[] = [];
    private rightTranData: any[] = [];
    private detailPage: pages = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };
    private showModal: boolean = false;
    private treeData: any[] = [
        {
            id: '-1',
            label: '全部选择',
            children: [
                {
                    id: '001',
                    label: '风控',
                },
                {
                    id: '002',
                    label: '投资',
                },
                {
                    id: '003',
                    label: '交易',
                },
                {
                    id: '004',
                    label: '合规风险',
                },
            ],
        },
    ];
    private operateType: string = '';
    private tranColumns: any[] = [
        {
            label: '条目编号',
            prop: 'entryCode',
            width: 80,
        },
        {
            label: '风险说明',
            prop: 'entryName',
            width: 165,
        },
        {
            label: '创建角色',
            prop: 'entryRoleCodeText',
            width: 165,
        },
    ];
    private queryVisible: boolean = false; // 条目权限维护查询框显示
    private queryDetailVisible: boolean = false;
    private delDetailVisible: boolean = false;
    // 组节点查询
    private queryForm = {
        entryRoleCode: '',
        entryRoleName: '',
        createUser: '',
    };
    // 子节点查询
    private queryDetailForm = {
        entryCode: '',
        entryName: '',
    };
    private selectedDetailList: string[] = []; // 选择表格数据
    private delDetailList: string[] = []; // 删除表格数据
    // private riskTrantableKey: number = 0;
    private isDisabled: boolean = false; // 是否全部权限
    mounted() {
        this.searchData();
    }

    // 左边栏选择节点
    private clickNode(data: any): void {
        this.cutInfo = data.label;
        this.selectNode = data.id;
        if (data.label != '全部选择') {
            this.getDataSourceRight(data.id, 'detail');
        }
    }

    /* *********************** 条目权限维护 start ********************* */
    /**
     * 查询数据
     *
     * @param type  'detail'：子节点
     * @private
     */
    private searchData(type?: string) {
        if (type === 'detail') {
            let tableDetailDataListTemp = this.handleFilterDetail(this.tableDetailDataList, this.queryDetailForm);
            this.detailPage.total = tableDetailDataListTemp.length;
            this.detailPage.currentPage = 1;
            this.tableDetailData = getCurrentPageData(tableDetailDataListTemp, this.detailPage.currentPage, this.detailPage.pageSize);
            this.queryDetailVisible = false;
            this.yh_message_success('查询成功');
        } else {
            this.tableData = this.handleFilter(this.tableDataList, this.queryForm);
            this.queryVisible = false;
            // this.yh_message_success('查询成功');
        }
    }

    // 根节点筛选数据
    private handleFilter(dataSource: any, param: any): any {
        if (!dataSource) {
            return dataSource;
        } else {
            return dataSource.filter(
                (item: any) =>
                    (item.entryRoleCode || '').toUpperCase().includes(param.entryRoleCode.toUpperCase()) &&
                    (item.entryRoleName || '').toUpperCase().includes(param.entryRoleName.toUpperCase()) &&
                    (item.createUser || '').toUpperCase().includes(param.createUser.toUpperCase())
            );
        }
    }

    private handleFilterDetail(dataSource: any, param: any): any {
        if (!dataSource) {
            return dataSource;
        } else {
            return dataSource.filter(
                (item: any) =>
                    (item.entryCode || '').toUpperCase().includes(param.entryCode.toUpperCase()) &&
                    (item.entryName || '').toUpperCase().includes(param.entryName.toUpperCase())
            );
        }
    }

    /**
     * 重置查询表单
     *
     * @param type  'detail'：重置子节点查询条件
     * @private
     */
    private resetForm(type: any) {
        if (type === 'detail') {
            (this.$refs.queryDetailForm as any).resetFields();
        } else {
            (this.$refs.queryForm as any).resetFields();
        }
    }

    /* ************************ 条目权限维护 end ********************* */

    /* ************************ 条目权限维护明细 start ********************* */
    // 获取明细表格勾选数据
    private handleSelectionDetailChange(val: any) {
        this.selectedDetailList = [];
        for (let i in val) {
            this.selectedDetailList.push(val[i].entryCode);
        }
    }

    // 判断删除类型
    private handleDetailRemove(val: any) {
        if (val === -1) {
            if (!this.selectedDetailList || this.selectedDetailList.length < 1) {
                this.yh_message_warn('未选择删除项');
                return;
            }
            this.delDetailList = this.selectedDetailList;
        } else {
            this.delDetailList = [];
            this.delDetailList.push(val);
        }
        this.delDetailVisible = true;
    }

    // 明细分页
    private currentDetailChange(val: number): void {
        this.detailPage.currentPage = val;
        this.tableDetailData = getCurrentPageData(this.tableDetailDataList, this.detailPage.currentPage, this.detailPage.pageSize);
    }

    // 获取条目组明细列表

    /* ************************ 条目权限维护明细 end ********************* */
    /**
     * 默认 编辑穿梭框 | 删除条目角色分类下条目
     *
     * @param type  del: 删除条目角色分类下条目
     * @private
     */
    private editDetailDialogConfirm(type: string): void {
        let needData = [];
        if (type === 'del') {
            let delSet = new Set(this.delDetailList);
            this.tableDetailDataList.map((item: any) => {
                if (!delSet.has(item.entryCode)) {
                    needData.push(item.entryCode);
                }
            });
            this.$axios.post('/entryRole/relation/bind', { entryRoleCodes: this.selectNode, grantCodes: needData }).then((res: any) => {
                this.yh_message_success('删除成功');
                this.delDetailVisible = false;
                this.getDataSourceRight(this.selectNode, 'detail');
            });
        } else {
            if (this.isDisabled) {
                needData = ['-1'];
            } else {
                const rightData = (this.$refs.tranTable as any).getRightAllData();
                rightData.map((item: any) => {
                    needData.push(item.entryCode);
                });
            }
            this.$axios.post('/entryRole/relation/bind', { entryRoleCodes: this.selectNode, grantCodes: needData }).then((res: any) => {
                this.yh_message_success('更新成功');
                this.showModal = false;
                this.getDataSourceRight(this.selectNode, 'detail');
            });
        }
    }

    private dialogClosed(): void {
        this.showModal = false;
    }

    // 条目权限修改完成回调
    private handleItemPermission(keys, value, action) {
        if (action === 'edit' || action === 'look') {
            this.showModal = true;
            this.operateType = action;
            this.getDataSourceRight(this.selectNode);
        } else if (action === 'confirm') {
            this.showModal = false;
        } else {
            this.showModal = false;
        }
    }

    /**
     * 获取右边数据列表 | 获取明细数据列表
     *
     * @param entryRoleCode
     * @param type  'detail': 明细数据
     * @private
     */
    private getDataSourceRight(entryRoleCode: string, type?: string): void {
        this.rightTranData = [];
        this.$axios.post('/entryRole/query/' + entryRoleCode).then((res: any) => {
            res.forEach(item => (item.key = item.entryCode));
            let entryList = res.sort((b, a) => b.entryCode.replace(/[^0-9]/gi, '') - a.entryCode.replace(/[^0-9]/gi, ''));
            entryList.forEach(element => {
                let entryRoleCodeText = '';
                if (element.entryRoleCode && element.entryRoleCode.length) {
                    let elArr = element.entryRoleCode.split(',');
                    entryRoleCodeText = elArr.map(item => EntryPower[item]).join(', ');
                }
                this.rightTranData.push({
                    ...element,
                    entryRoleCodeText,
                    isDisabled: element.entryRoleCode && element.entryRoleCode.includes(entryRoleCode),
                });
            });
            if (type != 'detail') {
                this.getLeftData(entryList);
            } else {
                this.tableDetailDataList = this.rightTranData;
                this.detailPage.total = this.rightTranData.length;
                this.tableDetailData = getCurrentPageData(this.tableDetailDataList, this.detailPage.currentPage, this.detailPage.pageSize);
            }
        });
    }

    /**
     * 获取左边数据列表
     */
    private getLeftData(filterData: any): void {
        let filterCodes = filterData.map(item => item.entryCode);
        this.$axios.post('/entryRole/query/filter', filterCodes).then((res: any) => {
            res.forEach(item => (item.key = item.entryCode));
            let entryList = res.sort((b, a) => b.entryCode.replace(/[^0-9]/gi, '') - a.entryCode.replace(/[^0-9]/gi, ''));
            entryList.forEach(element => {
                let entryRoleCodeText = '';
                if (element.entryRoleCode && element.entryRoleCode.length) {
                    let elArr = element.entryRoleCode.split(',');
                    entryRoleCodeText = elArr.map(item => EntryPower[item]).join(', ');
                }
                element.entryRoleCodeText = entryRoleCodeText;
            });
            this.leftTranData = entryList;
            this.isDisabled = !(this.leftTranData.length > 0);
        });
    }

    // // 是否拥有所有产品权限
    // private handleAllProduct(value: boolean): void {
    //     this.riskTrantableKey++;
    // }
}
</script>
<style lang="scss" scoped>
.pool-list {
    height: 100%;
}
/deep/ .el-dialog .el-dialog__body {
    max-height: 100vh;
}
/deep/ .editDialog .el-dialog .el-dialog__body {
    height: 500px;
}
</style>
